package com.felix.thread.atomic;

import lombok.Data;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Mutex
 *
 * @author xuejinhua
 * @date 2018/11/30 17:38
 */
public class Mutex {

    public static void main(String[] args) {
        TestMutex test = new TestMutex();
        int threadNum = 10;
        Thread[] threads = new Thread[threadNum];

        // 创建10个线程，让它们不断地去增加test.sum的值
        for (int i = 0; i < threadNum; i++) {
            Thread t = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    test.add();
                }
            });
            t.start();
            threads[i] = t;
        }
        for (Thread t : threads) {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(test.getSum());
    }
}

@Data
class TestMutex {
    private int sum = 0;
    private AtomicInteger mutex = new AtomicInteger(0);

    private static int MAX = 30_000;
    private static int STEP = 50;

    public void add() {
        if (!mutex.compareAndSet(0, 1)) {
            return;
        }
        if (sum >= MAX) {
            return;
        }
        try {
            // 这里sleep一下，增加线程切换的概率
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        sum += STEP;
        mutex.set(0);
    }
}
